package com.web.atmt.service.impl;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import com.web.atmt.bean.Attachment;
import com.web.atmt.bean.AttachmentType;
import com.web.atmt.service.AttachmentService;
import com.web.base.service.impl.BaseServiceImpl;

public class AttachmentServiceImpl extends BaseServiceImpl implements AttachmentService {

	@Override
    public AttachmentType getAttachmentType(String typeId) throws SQLException, IOException {
	    String sql = "select type_id as typeId, type_name as typeName, save_path as savePath,"
	    		   + "       max_size as maxSize, max_total as maxTotal, type_scope as typeScope"
	    		   + "  from attachment_type where type_id = ?";
	    return this.findObject(AttachmentType.class, sql, typeId);
    }

	@Override
    public List<Attachment> loadAttachment(String otherId, String typeId) throws SQLException, IOException {
	    String sql = "select file_id as \"id\", file_name as \"name\", file_type as \"type\", file_size as \"size\", -4 as status"
	    		   + "  from attachment where other_id = ? and type_id = ?";
	    return this.findAll(Attachment.class, sql, otherId, typeId);
    }

	@Override
	public String getUploadPath(String typeId) throws SQLException, IOException {
		String sql = "select save_path as path from attachment_type where type_id = ?";
		Attachment attach = this.findObject(Attachment.class, sql, typeId);

		if (attach != null) {
			return attach.getPath();
		}
		return null;
	}

	@Override
	public void addAttachment(String fileId, String fileName, String fileType, Integer fileSize, String saveName,
	        String otherId, String typeId) throws SQLException, IOException {
		String sql = "insert into attachment(file_id, file_name, file_type, file_size, save_name, is_saved, other_id, type_id)"
			       + "values (?, ?, ?, ?, ?, '0', ?, ?)";
		this.save(sql, fileId, fileName, fileType, fileSize, saveName, otherId, typeId);
	}

	@Override
	public List<Attachment> getRemoveFile(String fileIds) throws SQLException, IOException {
		String sql = "select b.save_path || a.save_name as path "
				   + "  from attachment a join attachment_type b on b.type_id = a.type_id"
				   + " where a.file_id in (" + fileIds + ")";
		return this.findAll(Attachment.class, sql);
	}

	@Override
    public void removeAttachment(String fileIds) throws SQLException, IOException {
	    String sql = "delete from attachment where file_id in (" + fileIds + ")";
	    this.delete(sql);
    }

	@Override
	public Attachment getDownloadFile(String fileId) throws SQLException, IOException {
		String sql = "select a.file_name as \"name\", b.save_path || a.save_name as path"
				   + "  from attachment a join attachment_type b on b.type_id = a.type_id"
				   + " where a.file_id = ?";
		List<Attachment> list = this.findAll(Attachment.class, sql, fileId);
		
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

}
